package com.bw.goods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.ResponseResult;
import com.bw.common.auth.JwtUtils;
import com.bw.common.auth.RsaUtils;
import com.bw.common.auth.UserInfo;
import com.bw.goods.entity.SysUser;
import com.bw.goods.entity.SysUserReq;
import com.bw.goods.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xingjinning
 * @since 2020-07-05
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("send/{phone}")
    public ResponseResult sendCode(@PathVariable("phone")String phone){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            result=userService.sendCode(phone);
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @PostMapping("login")
    public ResponseResult login(@RequestBody SysUserReq userReq){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String code = redisTemplate.boundValueOps("Y:" + userReq.getPhone()).get();
            if(null==code){
                result.setSuccess(false);
                result.setMessage("验证码过期");
                return result;
            }
            if(!code.equals(userReq.getCode())){
                result.setSuccess(false);
                result.setMessage("验证码错误");
                return result;
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("phone",userReq.getPhone());
            SysUser sysUser = userService.getOne(queryWrapper);
            PrivateKey privateKey = RsaUtils.getPrivateKey("D:\\1711A\\keys\\rsa.pri");
            UserInfo userInfo = new UserInfo();
            userInfo.setId(sysUser.getId());
            userInfo.setUsername(sysUser.getNickname());
            String token = JwtUtils.generateToken(userInfo, privateKey, 30);
            Map map = new HashMap();
            map.put("user",sysUser);
            map.put("token",token);
            result.setMessage("登陆成功");
            result.setResult(map);
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @GetMapping("getname")
    public ResponseResult getname(){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            result.setResult(userService.list());
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }

}
